package cn.chencq.moudle.job.task;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.chencq.moudle.lottery.entity.Lottery;
import cn.chencq.moudle.lottery.service.LotteryService;
import cn.chencq.moudle.mail.service.MailService;
import cn.chencq.utils.LotteryApiUtils;
import cn.chencq.utils.redis.RedisKey;
import cn.chencq.utils.redis.RedisUtils;

@Component("testTask")
public class TestTask {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private LotteryService lotteryService;

	@Autowired
	private MailService mailService;

	@Autowired
	private RedisUtils redisUtils;

	private static final String MAX_LOTTERY_ID = "max:lottery:id:";

	private static final String TO_EMAIL = "ccq@chencq.cn";

	// 定时任务只能接受一个参数；如果有多个参数，使用json数据即可
	public void test(String params) {
		logger.info("我是带参数的test方法，正在被执行，参数为：" + params);

		try {
			Thread.sleep(1000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void test2() {
		logger.info("我是不带参数的test2方法，正在被执行");
	}

	public void spiderLottery(String lotteryType) {
		String key = MAX_LOTTERY_ID + lotteryType;
		long maxLotteryId = 0L;
		if (redisUtils.exists(key)) {
			maxLotteryId = redisUtils.get(key, Long.class);
		}

		List<Lottery> list = LotteryApiUtils.getLotteryList(lotteryType, 1, null);
		List<Lottery> updateList = new ArrayList<>();
		long temp = 0L;
		for (Lottery lottery : list) {
			long lotteryId = Long.parseLong(lottery.getLotteryId());
			if (lotteryId > maxLotteryId) {
				updateList.add(lottery);
				if (lotteryId > temp) {
					temp = lotteryId;
				}
			}
		}
		
		if (temp > 0) {
			redisUtils.set(key, temp);
		}

		lotteryService.batchSaveOrUpdate(list);
		logger.info("爬虫任务开始执行，参数为：{}, 爬取数据条数:{}, 更新数据条数:{}", lotteryType, (null != list ? list.size() : 0),
				updateList.size());
	}

	public void spiderLotteryMissing(String lotteryType) {
		String url = null;
		String subject = "";
		switch (lotteryType) {
		case "1":
			url = "http://m.dashen28.com/xingyun28/jiange/";
			subject = "北京幸运28预警";
			break;
		case "3":
			url = "http://m.dashen28.com/jianada28/jiange/";
			subject = "加拿大28预警";
			break;
		default:
			break;
		}

		int limit = getLimit();
		Document doc = null;
		try {
			doc = Jsoup.connect(url).get();
			List<Integer> result = new ArrayList<Integer>();
			List<Element> headers = doc.select("header h1.am-header-title");
			String title = headers.get(0).html();
			List<Element> els = doc.select("div.mustlook table td span i");
			for (Element e : els) {
				String r = e.html();
				result.add(Integer.parseInt(r));
			}
			String[] arr = { "单", "双", "小", "大", "大单", "大双", "小单", "小双" };
			int num = 0;
			for (int i = 0; i < 8; i++) {
				num = result.get(i);
				if (num > limit) {
					subject = subject + "-" + title + (arr[i]) + "(" + num + ")";
					mailService.sendSimpleMail(TO_EMAIL, subject, "详情查看" + url);
					break;
				}
			}
		} catch (Exception e) {
			logger.error("监控数据异常", e);
		}
	}

	private int getLimit() {
		int limit = 12;
		try {
			limit = redisUtils.get(RedisKey.LOTTERY_OMISSION_ANALYSIS_LIMIT, Integer.class);
		} catch (Exception e) {
		}
		return limit;
	}
}
